package com.leo.ibatis.demo.dao.ibatis;

import java.util.List;

import org.springframework.dao.DataAccessException;
import org.springframework.orm.ibatis.support.SqlMapClientDaoSupport;
import org.springframework.util.Assert;

import com.leo.ibatis.demo.criteria.AccountCriteria;
import com.leo.ibatis.demo.dao.AccountDao;
import com.leo.ibatis.demo.domain.Account;
import com.leo.ibatis.demo.util.Paging;

public class AccountDaoImpl extends SqlMapClientDaoSupport implements AccountDao {

	public void insert(Account account) throws DataAccessException {
		getSqlMapClientTemplate().insert("Account.insert", account);
	}

	public int update(Account account) throws DataAccessException {
		int actualRowsAffected = 1;

		getSqlMapClientTemplate().update("Account.update", account, actualRowsAffected);

		return actualRowsAffected;
	}

	public int delete(String userid) throws DataAccessException {
		int actualRowsAffected = 1;

		getSqlMapClientTemplate().delete("Account.delete", userid, actualRowsAffected);

		return actualRowsAffected;
	}

	public Account select(String userid) throws DataAccessException {
		return (Account) getSqlMapClientTemplate().queryForObject("Account.select", userid);
	}

	@SuppressWarnings("unchecked")
	public List<Account> list(AccountCriteria accountCriteria) throws DataAccessException {
		Assert.notNull(accountCriteria, "accountCriteria must not be null");
		
		return getSqlMapClientTemplate().queryForList("Account.list", accountCriteria);
	}

	@SuppressWarnings("unchecked")
	public List<Account> listOnPage(AccountCriteria accountCriteria) throws DataAccessException {
		Assert.notNull(accountCriteria, "accountCriteria must not be null");
		Assert.notNull(accountCriteria.getPaging(), "paging must not be null");
		
		int totalResults = count(accountCriteria);
		Paging paging = accountCriteria.getPaging();
		paging.setTotalResults(totalResults);
		
		return getSqlMapClientTemplate().queryForList("Account.list", accountCriteria, paging.getFirstResult(), paging.getMaxResults());
	}

	public int count(AccountCriteria accountCriteria) throws DataAccessException {
		Assert.notNull(accountCriteria, "accountCriteria must not be null");
		
		return ((Integer) getSqlMapClientTemplate().queryForObject("Account.count", accountCriteria)).intValue();
	}

}
